import React, {PureComponent} from 'react';
import print from '../../assets/svg/actionBar/print.svg';
import pdf from '../../assets/svg/actionBar/pdf.svg';
import word from '../../assets/svg/actionBar/word.svg';
import excel from '../../assets/svg/actionBar/excel.svg';
import excelPaging from '../../assets/svg/actionBar/excel-paging.svg';
import styles from './index.module.less';
import {Button, Divider, Dropdown, Menu, Popover, Spin, Tooltip, } from "antd";

import { isEmpty, isFunction} from "lodash-es";
import {buildChart, getChartImg, } from "../Chart";
import ButtonComp from "../ButtonComp"
import {getTdHeight} from "./helper";
import SheetSearchComp from "./SheetSearchComp";
import {isObjectValEqual} from "jh-utils";
import BaseComp from "../Base/BaseComp"

function enhancePop(PopComp) {
    return (props) => (
        <div style={{marginRight: 12}}>
            <PopComp
                getPopupContainer={triggerNode => triggerNode.parentNode || document.body}
                arrowPointAtCenter
                {...props}
            />
        </div>
    )
}

const InnerTooltip = enhancePop(Tooltip);
const InnerDropdown = enhancePop(Dropdown);

function SvgIcon(props) {
    const {src = '', alt = '', loading, ...restProps} = props;
    return <div {...restProps}>
        <Spin spinning={loading} size={'small'}>
            <div className={styles.svgIcon}>

                <img src={src} alt={alt}/>
            </div>
        </Spin>
    </div>
}


export default class ActionBar extends BaseComp {

    constructor(props) {
        super(props);
        this.state = {
            visible: !isEmpty(props.searchFormConf) ? true : false,
            apiMap: {
                print: {api: '/api/bi/pdf/build_pdf', extraParams: {forPrint: true}, loading: false}, // 额外参数 是否打印
                pdf: {api: '/api/bi/pdf/build_pdf', extraParams: {forPrint: false}, loading: false},
                word: {api: '/api/bi/word/build_word', loading: false},
                excelExport: {api: '/api/bi/excel/export', loading: false},
                excel: {api: '/api/bi/excel/sheet', loading: false},
                excelPaging: {api: '/api/bi/excel/paging', loading: false},
            }
        }
    }

    componentDidUpdate(preProps, preState){
        if(!isObjectValEqual(preProps, this.props, ['searchFormConf'])){
            if(!isEmpty(this.props.searchFormConf)){
                this.setState({visible: true})
            }
        }
    }

    componentDidMount(){
        let { onRef } = this.props;
        isFunction(onRef) && onRef(this);

    }

    hdlExport = (type, action = true) => () => {

        const {reportCode,  getSearchParams} = this.props;
        let fetchReturn = getSearchParams && getSearchParams();
        if(fetchReturn instanceof Promise){
            fetchReturn.then(values=>{
                if(values !== false){
                    this.fetchExport(type, action, values)
                }

            })
        }
    };

    fetchExport(type, action = true, searchParams){
        const {reportCode} = this.props;
        const {apiMap} = this.state;
        if (!type && isEmpty(type)) return;

        const reqType = apiMap[type];
        const {api, extraParams = {}} = reqType;
        const paramsObj = {reportCode, parameters: searchParams, ...extraParams};

        const nApiMap = {...apiMap};
        nApiMap[type] = {...nApiMap[type], loading: true};
        this.setState({apiMap: {...nApiMap}});
        let rowHeights = getTdHeight();
        if(!isEmpty(rowHeights)){
            paramsObj.rowHeights = rowHeights
        }
        this.jsonPost(`/api/bi/designer/upload_params`,paramsObj).then(rsp => {
            if (rsp && 200 === rsp.status) {
                // window.openWin(`${api}`);
                this.fetchBuildData(api, action);
            }
        }).finally(() => {
            nApiMap[type] = {...nApiMap[type], loading: false};
            this.setState({apiMap: {...nApiMap}});
        })
    }

    /**
     * 导出
     * @param api
     */
    fetchBuildData(api, action){
        this.jsonPost('/api/bi/chart/review_build_chart_data').then(res=>{
            if(res && res.status == 200 && res.data){
                let { chartDatas, design} = res.data;
                let cellChart = buildChart(chartDatas, design);
                // console.log('cellChart:',cellChart);
                // console.log('design:',JSON.parse(design));
                getChartImg(cellChart,500).then(imgs=>{
                    // console.log('Base64-imgs:', imgs);

                    this.jsonPost('/api/bi/chart/store_chart_base64',{chartBase64s :imgs}).then(res=>{
                        if(res && res.status == 200){
                            if(action === true){
                                window.openWin(`${api}`)
                            }else if(isFunction(action)) {
                                action(api);
                            }
                        }
                    })
                });

            }
        })
    }

    popoverHdl(){
        this.setState({
            visible: !this.state.visible
        })
    };

    handleOk(){
        let { fetchSheet } = this.props;
        const {getSearchParams} = this.props;
        getSearchParams && getSearchParams().then(values => {
            if(values !== false){
                this.setState({visible: false});
                fetchSheet && fetchSheet();
            }
        });

    }
    handleReset(){
        let { handleReset } = this.props;
        handleReset && handleReset();
    }

    mainRender() {
        const {apiMap, visible = false} = this.state;
        let { searchFormConf } = this.props;
        return <div className={styles.actionBarWrap}>
            <div className={styles.actionBar}>
                <InnerTooltip placement="bottom" title={'打印'}>
                    <SvgIcon src={print} alt={'print'} onClick={this.hdlExport('print')} loading={apiMap['print'].loading}/>
                </InnerTooltip>
                <InnerTooltip placement="bottom" title={'pdf'}>
                    <SvgIcon src={pdf} alt={'pdf'} onClick={this.hdlExport('pdf')} loading={apiMap['pdf'].loading}/>
                </InnerTooltip>
                <InnerTooltip placement="bottom" title={'word'}>
                    <SvgIcon src={word} alt={'word'} onClick={this.hdlExport('word')} loading={apiMap['word'].loading}/>
                </InnerTooltip>
                <InnerDropdown
                    overlay={
                        <Menu>
                            <Menu.Item>
                                <div onClick={this.hdlExport('excelExport')}>导出</div>
                            </Menu.Item>
                            <Menu.Item>
                                <div onClick={this.hdlExport('excel')}>分sheet导出</div>
                            </Menu.Item>
                            <Menu.Item>
                                <div onClick={this.hdlExport('excelPaging')}>分页导出</div>
                            </Menu.Item>
                        </Menu>
                    }
                    placement="bottomCenter"
                    arrow
                >
                    <SvgIcon
                        src={excel}
                        alt={'excel'}
                        loading={
                            apiMap['excelExport'].loading
                            || apiMap['excel'].loading
                            || apiMap['excelPaging'].loading
                        }/>
                </InnerDropdown>
            </div>
            <div className={styles.btnGroup}>
                {
                    isEmpty(searchFormConf) ?
                        <Button type={'primary'} htmlType="submit" loading={this.props.loadingReview}>{this.formatMsgByCn('查询')}</Button> :
                        <Popover placement={'rightTop'}
                                 visible={visible}
                                 onVisibleChange={visible => {
                                     this.setState({visible});
                                 }}
                                 overlayStyle={{
                                     zIndex: 1010
                                 }}
                                 getPopupContainer = {triggerNode => (triggerNode && triggerNode.parentNode || document.body)}
                                 content={<SheetSearchComp
                                     handleOk={this.handleOk.bind(this)}
                                     handleCancel={this.popoverHdl.bind(this)}
                                     handleReset={this.handleReset.bind(this)}
                                     searchFormConf={searchFormConf}/>}
                                 trigger={'click'}>
                            <Button type={'link'}
                                    onClick={this.popoverHdl.bind(this)}
                                    loading={this.props.loadingReview}>{this.formatMsgByCn('高级查询')}</Button>
                        </Popover>
                }
                {
                    this.props.isPreview !== true && this.props.docChecked === true &&
                    <ButtonComp style={{marginLeft:16}} loading={this.props.loadingReview} onClick={this.props.saveForSynDoc}>
                        {this.formatMsgByCn("保存为我的文档")}
                    </ButtonComp>
                }
            </div>
        </div>
    }
}

